// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  console.log(event)
  // event.device_logicid
  // event.gprs_number
  var n = Date.now()
  var date = new Date(n)
  var time=parseInt(date.getTime()/1000)


  if(event.level==1){
    try {
      return await db.collection('scanCode').add({
        // data 字段表示需新增的 JSON 数据

        data: {
          openidThree: "",
          openidFour: "",
          openidFive: "",
          brandidTwo:event.brandid,
          brandidThree:"",
          brandidFour: "",
          brandidFive: "",
          scanCodeTimeThree:"",
          scanCodeTimeFour:"",
          scanCodeTimeFive:"",
          isSubmitThree:false,
          isSubmitFour:false,
          isSubmitFive:false,
          device_logicid:event.device_logicid,
          gprs_number:event.gprs_number
          },
      })
    } catch(e) {
      console.error(e)
    }
  }else if(event.level==3){
    try {
      return await db.collection('scanCode')
      .where({
        device_logicid:event.device_logicid,
        gprs_number:event.gprs_number
      })
      .update({
        data: {
          openidThree:wxContext.OPENID,
          brandidThree:event.brandid,
          scanCodeTimeThree:time,
          },
      })
    } catch(e) {
      console.error(e)
    }
  }else if(event.level==4){
    try {
      return await db.collection('scanCode')
      .where({
        device_logicid:event.device_logicid,
        gprs_number:event.gprs_number
      })
      .update({
        data: {
          openidFour:wxContext.OPENID,
          brandidFour:event.brandid,
          scanCodeTimeFour:time,
          },
      })
    } catch(e) {
      console.error(e)
    }
  }else if(event.level==5){
    try {
      return await db.collection('scanCode')
      .where({
        device_logicid:event.device_logicid,
        gprs_number:event.gprs_number
      })
      .update({
        data: {
          openidFive:wxContext.OPENID,
          brandidFive:event.brandid,
          scanCodeTimeFive:time,
          },
      })
    } catch(e) {
      console.error(e)
    }
  }else{
    return -1
  }
}